/*
 * Copyright 2008 Nathan C Jones
 * 
 * This file is part of Fivehundred.
 * 
 * Fivehundred is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * Fivehundred is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * Fivehundred. If not, see <http://www.gnu.org/licenses/>. 
 */

package com.googlecode.fivehundred.svg;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.JPEGTranscoder;

/**
 * Creates a raster image from an SVG document.
 * 
 * @author Nathan C Jones
 */
public class SVGRasterizer {

	/**
	 * Create a rasterised image from the SVG file at the given URL.
	 * 
	 * @param svgURL the location of the SVG file to rasterize.
	 * @param width the size of the image to generate from the SVG.
	 * @return an image generated from SVG with the given width.
	 * @throws SVGRasteriserException if the SVG image could not be rasterized.
	 */
	public Image createImage(URL svgURL, float width) {
		TranscoderInput input = new TranscoderInput(svgURL.toString());
		Rasterizer r = new Rasterizer();
		r.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(width));
		try {
			r.transcode(input, null);
		} catch (TranscoderException e) {
			throw new SVGRasteriserException(e);
		}
		return r.raster;
	}

	/**
	 * An image transcoder that stores the resulting image.
	 */
	private static class Rasterizer extends ImageTranscoder {
		private Image raster;

		public BufferedImage createImage(int w, int h) {
			return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
		}

		public void writeImage(BufferedImage img, TranscoderOutput output) throws TranscoderException {
			raster = img;
		}
	}
}
